<template>
  <div class="kcjxzj-summary-create">
    <div class="page-header">
      <h1>新建课程教学总结</h1>
      <div class="actions">
        <el-button @click="router.go(-1)">
          <el-icon><Back /></el-icon> 返回
        </el-button>
      </div>
    </div>
    
    <el-card class="form-card" v-loading="loading">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" label-position="left">
        <el-tabs type="card">
          <el-tab-pane label="基本信息">
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" style="width: 100%" :disabled="!!preSelectedMission">
                <el-option v-for="course in courses" :key="course.id" :label="course.name" :value="course.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="termId">
              <el-select v-model="form.termId" placeholder="请选择学期" style="width: 100%" :disabled="!!preSelectedMission">
                <el-option v-for="term in terms" :key="term.id" :label="term.name" :value="term.id" />
              </el-select>
            </el-form-item>
            <!-- 培养层次和专业信息现在通过课程关联获取，不再需要单独选择 -->
            <el-form-item label="教学任务" prop="teachingMissionIds">
              <el-select v-model="form.teachingMissionIds" multiple placeholder="请选择教学任务" style="width: 100%" :disabled="!!preSelectedMission">
                <el-option v-for="tm in filteredTeachingMissions" :key="tm.id" :label="tm.course.name + ' - ' + tm.teachers.map(t => t.name).join(',')" :value="tm.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="开课单位" prop="departmentIds">
              <el-select v-model="form.departmentIds" multiple placeholder="请选择开课单位" style="width: 100%">
                <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id" />
              </el-select>
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="教材信息">
            <el-form-item label="使用教材" prop="textbook">
              <el-input type="textarea" v-model="form.textbook" placeholder="请输入使用教材" rows="4" />
            </el-form-item>
            <el-form-item label="教材类别" prop="textbookType">
              <el-input v-model="form.textbookType" placeholder="请输入教材类别" />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="教学总结">
            <el-form-item label="教学设计与实施" prop="designAndImplementation">
              <RichTextEditor 
                v-model="form.designAndImplementation" 
                placeholder="请输入教学设计与实施情况，包括教学目标、教学内容、教学方法、教学过程等" 
                height="350px"
              />
            </el-form-item>
            <el-form-item label="考试考核" prop="assessment">
              <RichTextEditor 
                v-model="form.assessment" 
                placeholder="请输入考试考核情况，包括考核方式、考核标准、成绩分析等" 
                height="350px"
              />
            </el-form-item>
            <el-form-item label="教学反思与改进" prop="reflectionAndImprovement">
              <RichTextEditor 
                v-model="form.reflectionAndImprovement" 
                placeholder="请输入教学反思与改进建议，包括教学效果分析、存在问题、改进措施等" 
                height="350px"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        
        <div class="form-actions">
          <el-button type="info" @click="onSaveDraft" :loading="savingDraft">
            暂存
          </el-button>
          <el-button type="primary" @click="onSubmit" :loading="submitting">
            <el-icon><Check /></el-icon> 提交审核
          </el-button>
          <el-button @click="onCancel">
            <el-icon><Close /></el-icon> 取消
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import { createKcjxzj } from '@/api/course-teaching-summary';
import RichTextEditor from '@/components/common/RichTextEditor.vue';
import { 
  courseApi,
  termApi,
  teachingMissionApi,
  departmentApi
} from '@/api/base-data';
import { Check, Close, Back } from '@element-plus/icons-vue';

export default {
  name: 'CreateKcjxzj',
  components: {
    Check,
    Close,
    Back,
    RichTextEditor
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formRef = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const savingDraft = ref(false);
    const preSelectedMission = ref(null);
    
    const form = ref({
      courseId: '',
      termId: '',
      teachingMissionIds: [],
      departmentIds: [],
      textbook: '',
      textbookType: '',
      designAndImplementation: '',
      assessment: '',
      reflectionAndImprovement: ''
    });

    // 获取基础数据
    const courses = ref([]);
    const terms = ref([]);
    const teachingMissions = ref([]);
    const departments = ref([]);

    // 根据选择的学期过滤教学任务
    const filteredTeachingMissions = computed(() => {
      if (!form.value.termId) {
        return teachingMissions.value;
      }
      return teachingMissions.value.filter(tm => tm.term?.id === form.value.termId);
    });

    // 获取当前学期并设置为默认值
    const getCurrentTerm = (terms) => {
      // 查找标记为当前学期的记录
      const currentTerm = terms.find(term => term.isCurrent === true || term.is_current === true);
      
      // 如果没有找到当前学期，返回null（不设置默认值）
      if (!currentTerm && terms.length > 0) {
        console.warn('未找到标记为当前学期的数据，请在后台设置当前学期');
      }
      
      return currentTerm || null;
    };

    const fetchBaseData = async () => {
      loading.value = true;
      try {
        const [coursesData, termsData, teachingMissionsData, departmentsData] = await Promise.all([
          courseApi.getAllCourses(),
          termApi.getAllTerms(),
          teachingMissionApi.getMyTeachingMissions(), // 使用权限受限的API
          departmentApi.getAllDepartments()
        ]);
        
        courses.value = coursesData;
        terms.value = termsData;
        // 权限受限的API返回分页数据，需要提取content
        teachingMissions.value = teachingMissionsData.content || teachingMissionsData;
        departments.value = departmentsData;
        
        // 设置当前学期为默认值
        const currentTerm = getCurrentTerm(terms.value);
        if (currentTerm) {
          form.value.termId = currentTerm.id;
        }
      } catch (error) {
        console.error('获取基础数据失败:', error);
        ElMessage.error('获取基础数据失败');
      } finally {
        loading.value = false;
      }
    };

    // 从URL参数获取教学任务ID并预填表单
    const initFromSelectedMission = async (missionId) => {
      if (!missionId) return;
      
      try {
        // 查找对应的教学任务
        const mission = teachingMissions.value.find(m => m.id === Number(missionId));
        if (!mission) {
          console.error(`未找到ID为${missionId}的教学任务`);
          ElMessage.warning('未找到指定的教学任务');
          return;
        }
        
        preSelectedMission.value = mission;
        
        // 预填课程、学期和教学任务ID
        form.value.courseId = mission.course?.id;
        form.value.termId = mission.term?.id;
        form.value.teachingMissionIds = [Number(missionId)];
        
        // 如果课程有关联的部门，预填部门ID
        if (mission.departments && mission.departments.length > 0) {
          form.value.departmentIds = mission.departments.map(dept => dept.id);
        }
        
        // 注意：专业和培养层次信息现在通过course关联获取，不再直接设置
        
        ElMessage.success('已自动填入教学任务相关信息');
        
      } catch (error) {
        console.error('初始化教学任务数据失败:', error);
        ElMessage.error('初始化教学任务数据失败');
      }
    };

    // 从课程列表参数初始化表单
    const initFromCourseParams = () => {
      const { courseId, termId, teachingMissionIds } = route.query;
      
      if (courseId) {
        form.value.courseId = parseInt(courseId);
      }
      if (termId) {
        form.value.termId = parseInt(termId);
      }
      if (teachingMissionIds) {
        form.value.teachingMissionIds = teachingMissionIds.split(',').map(id => parseInt(id));
      }
    };

    const rules = {
      courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
      termId: [{ required: true, message: '请选择学期', trigger: 'change' }],
      // 暂存时不需要全部字段都填写
      // 其他字段在正式提交时验证
    };

    // 暂存功能（保存为草稿）
    const onSaveDraft = async () => {
      try {
        savingDraft.value = true;
        
        // 暂存时只需要基本的课程和学期信息
        if (!form.value.courseId || !form.value.termId) {
          ElMessage.warning('请至少选择课程和学期');
          return;
        }
        
        // 创建草稿状态的总结（statusId = 1）
        const draftData = {
          ...form.value,
          statusId: 1 // 草稿状态
        };
        
        await createKcjxzj(draftData);
        ElMessage.success('暂存成功');
        
        // 返回到课程总结浏览页面
        router.push('/kcjxzj/summary-browse');
      } catch (error) {
        console.error('暂存失败:', error);
        ElMessage.error('暂存失败');
      } finally {
        savingDraft.value = false;
      }
    };

    const onSubmit = async () => {
      try {
        await formRef.value.validate();
        submitting.value = true;
        
        // 提交审核状态（statusId = 2）
        const submitData = {
          ...form.value,
          statusId: 2 // 待审核状态
        };
        
        await createKcjxzj(submitData);
        ElMessage.success('提交审核成功');
        
        // 返回到课程总结浏览页面
        router.push('/kcjxzj/summary-browse');
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      } finally {
        submitting.value = false;
      }
    };

    const onCancel = () => {
      // 返回课程总结浏览页面
      router.push('/kcjxzj/summary-browse');
    };

    onMounted(async () => {
      await fetchBaseData();
      
      // 初始化表单数据
      if (route.query.courseId) {
        // 从课程列表传递的参数初始化
        initFromCourseParams();
      } else if (route.query.missionId) {
        // 如果有missionId查询参数，初始化表单数据（保持向后兼容）
        await initFromSelectedMission(route.query.missionId);
      }
    });

    return {
      form,
      formRef,
      rules,
      loading,
      submitting,
      savingDraft,
      preSelectedMission,
      courses,
      terms,
      teachingMissions,
      filteredTeachingMissions,
      departments,
      onSaveDraft,
      onSubmit,
      onCancel,
      router
    };
  }
};
</script>

<style scoped>
.kcjxzj-summary-create {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  margin-left: auto;
}

.form-card {
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.form-actions button {
  min-width: 120px;
  margin: 0 10px;
}

:deep(.el-tabs__header) {
  margin-bottom: 25px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>
